
package com.smth.infobox.compoments;

import com.smth.infobox.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.webkit.WebView;

public class BaseWebViewActivity extends Activity {

    protected WebView webView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setContentView(R.layout.webview);
        webView = (WebView) findViewById(R.id.wv);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setLoadsImagesAutomatically(true);
    }

    protected boolean canShowHome() {
        return webView.canGoBack();
    }

    protected void showHome() {
        while (webView.canGoBack()) {
            webView.goBack();
        }
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        menu.clear();
        super.onPrepareOptionsMenu(menu);
        if (canShowHome()) {
            menu.add(Menu.NONE, 0, Menu.NONE, R.string.home).setIcon(R.drawable.ic_menu_home);
        }
        menu.add(Menu.NONE, 1, Menu.NONE, R.string.reload).setIcon(R.drawable.ic_menu_refresh);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case 0:
                showHome();
                break;
            case 1:
                webView.reload();
                break;
        }

        return super.onOptionsItemSelected(item);
    }

    protected void onDestroy() {
        webView.destroy();
        super.onDestroy();
    }

    protected boolean handleSpeicalKey(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (webView.canGoBack()) {
                webView.goBack();
                return true;
            } else {
                finish();
                return false;
            }
        }
        return false;
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (handleSpeicalKey(keyCode, event)) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
